<template>
  <a-spin :spinning="loading">
    <div v-if="labelList.length" class="entity-label">
      <div v-for="(item, index) in labelList" :key="index" class="entity-label-wrap" @click.stop="handleClick(item)">
        <div class="entity-label-item" :style="colorFun(item?.color)">
          <div class="entity-label-title" :title="item?.name">{{ item?.name }}</div>
          <div class="entity-label-features">
            <div v-if="index < 10" class="shortcut-key-wrap">
              <shortcut-key
                :is-click-trigger="false"
                :keys="`${keyNumFun(index)},num_${keyNumFun(index)}`"
                :key-name="`${keyNumFun(index)}`"
                :data="item"
                @trigger="shortcutKeyTrigger"
              />
            </div>
            <div class="icon-btn-list">
              <a-button type="text" class="icon-only-btn" @click.stop="handleSkipUp(item)">
                <i class="iconfont icon-skip-up-line"></i>
              </a-button>
              <a-button v-if="isEditable" type="text" class="icon-only-btn" @click.stop="handleUpdate(item)">
                <i class="iconfont icon-edit-line"></i>
              </a-button>
              <a-button v-if="isEditable" type="text" class="icon-only-btn" @click.stop="handleDelete(item)">
                <i class="iconfont icon-delete-bin-6-line"></i>
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <default-image v-else title="暂无内容" />
  </a-spin>

  <entity-label-form
    ref="entityLabelFormRef"
    label-info="已标注的数据将会同步修改"
    :title="labelFormTitle"
    @on-submit="onEntityLabelFormSubmit"
  />
</template>

<script setup lang="ts">
  import { Modal } from 'ant-design-vue'
  import { message } from 'ant-design-vue'
  import { inject, Ref, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import { textLabelTagApi } from '@/services/index'
  import { hexToRgb } from '@/utils/index'

  import { useLabelResultListStore } from '../../dmp-text/store/index'
  import EntityLabelForm from '../EntityLabelForm.vue'
  import { MarkTaskLabelRes } from './types'

  export interface EntityLabelProps {
    taskInfo: any
    // 筛选值
    searchValue?: string
    // 类型
    type?: 'entity' | 'textTriplet'
  }
  const props = withDefaults(defineProps<EntityLabelProps>(), {
    searchValue: '',
    type: 'textTriplet'
  })

  const emits = defineEmits<{
    (event: 'shortcutKeyTrigger', data: any): void
    (event: 'delete', data: any): void
    (event: 'update', data: any): void
    (event: 'clickLabel', data: any): void
  }>()

  // 是否可编辑
  const isEditable = inject<Ref<boolean>>('isEditable') || ref(true)

  const labelResultListStore = useLabelResultListStore()
  const entityLabelFormRef = ref<InstanceType<typeof EntityLabelForm>>()

  const labelList = ref<MarkTaskLabelRes[]>([])
  const { loading, runAsync: runGetLabelList } = useRequest(textLabelTagApi.entityList)
  const getLabelList = async (params?: any) => {
    const res: any = await runGetLabelList({
      name: props.searchValue,
      taskId: props.taskInfo.id,
      ...params
    })
    labelList.value = res.data
  }

  const labelFormTitle = ref('创建标签')

  // 处理颜色
  const colorFun = (color?: string) => {
    return {
      color: hexToRgb(color),
      background: hexToRgb(color, 0.08)
    }
  }

  /**
   * 快捷键触发
   */
  const shortcutKeyTrigger = (item: any) => {
    emits('shortcutKeyTrigger', { ...item, ...item.data })
  }

  /**
   * 置顶
   */
  const handleSkipUp = async (item: any) => {
    labelList.value = labelList.value.filter(label => label.id !== item.id)
    labelList.value.unshift(item)
    message.success('置顶成功')
  }

  /**
   * 点击标签
   */
  const handleClick = (item: any) => {
    emits('clickLabel', item)
  }

  /**
   * 删除
   */
  const handleDelete = (item: any) => {
    Modal.confirm({
      title: '确认删除？',
      content: '当前标签及当前标注任务中使用此标签的标注信息将被删除，且不可恢复，请确认操作',
      centered: true,
      async onOk() {
        await deleteTag()
        emits('delete', item)
      }
    })

    const deleteTag = async () => {
      await textLabelTagApi.del(
        {},
        {
          urlParams: {
            id: item.id
          },
          isAddUid: true
        }
      )

      labelResultListStore.removeRelationResultsByEntityLabel(item.id)
      message.success('删除成功')
      getLabelList()
    }
  }

  /**
   * 编辑
   */
  const handleUpdate = (item: any) => {
    labelFormTitle.value = props.type === 'entity' ? '编辑标签' : '编辑实体标签'
    entityLabelFormRef.value?.open(item)
  }
  // 实体标签表单提交
  const onEntityLabelFormSubmit = async (formState: any) => {
    try {
      await textLabelTagApi.edit(
        {
          id: formState.id,
          taskId: props.taskInfo.id,
          name: formState.name,
          color: formState.color
        },
        {
          isAddUid: true,
          headers: {
            'hide-message': 'true'
          }
        }
      )

      // 同步修改标注结果中的标签信息
      labelResultListStore.updateEntityLabelByLabelId(formState.id, {
        labelName: formState.name,
        labelColor: formState.color
      })
      message.success('标签编辑成功')
      emits('update', formState)
      entityLabelFormRef.value?.close()
      getLabelList()
    } catch (error: any) {
      // const msg = props.type === 'entity' ? '标签名重复' : '实体标签名重复'
      // if (error?.code === 'MARKTAG-100003') {
      //   message.error(msg)
      // } else {
      error?.message && message.error(error?.message)
      // }
    } finally {
      entityLabelFormRef.value?.hideLoading()
    }
  }

  /**
   * 处理索引
   * @param number 索引
   */
  const keyNumFun = (index: number) => {
    return ++index > 9 ? 0 : index
  }

  /**
   * 搜索
   */
  const handleSearch = (searchValue?: string) => {
    getLabelList({
      name: searchValue
    })
  }

  watch(
    () => props.taskInfo?.id,
    () => {
      getLabelList()
    }
  )

  defineExpose({
    search: handleSearch,
    getLabelList
  })
</script>

<style lang="less" scoped>
  .entity-label {
    display: flex;
    padding: 8px 0;
    width: 100%;
    flex-direction: column;
    gap: 4px 0;
    box-sizing: border-box;

    .entity-label-wrap {
      display: flex;
      align-items: center;
      padding: 0 24px;
      height: 44px;
      cursor: pointer;
      flex-shrink: 0;

      &:hover {
        background: #f5f5f5;

        .icon-btn-list {
          display: flex !important;
        }

        .shortcut-key-wrap {
          display: none !important;
        }
      }

      .entity-label-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 6px;
        width: 100%;
        height: 36px;
        background: rgba(24, 104, 233, 0.08);
        border: 1px solid rgba(0, 0, 0, 0.05);
        border-radius: 6px;

        .entity-label-title {
          height: 36px;
          font-size: 14px;
          font-weight: 400;
          line-height: 36px;
          .elliptical-1();
        }

        .entity-label-features {
          margin-left: 4px;

          .shortcut-key-wrap {
            display: block;
          }

          .icon-btn-list {
            display: none;
            gap: 0 16px;
          }
        }
      }
    }
  }
</style>
